package com.myframe.www.net;

import android.content.Context;
import android.net.ParseException;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.myframe.www.model.remote.bean.ServerFailureBean;
import com.yong.android.framework.utils.log.SLog;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import javax.net.ssl.SSLHandshakeException;

import okhttp3.ResponseBody;


/**
 * Description:
 * Created by Andy Hong on 10/19/2017.
 */

public class FailureBean {
    private Throwable e;
    private ServerFailureBean serverFailureBean;
    private static Gson gson = new Gson();

    public FailureBean(Throwable mThrowable) {
        this.e = mThrowable;
        serverFailureBean = findServerFailureBean(mThrowable);
    }

    public boolean isServerFailure() {
        return serverFailureBean != null;
    }

    public ServerFailureBean getServerFailureBean() {
        return serverFailureBean;
    }

    private ServerFailureBean findServerFailureBean(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            if (code == 400 ||
                    code == 403 || code == 404 || code == 405 ||
                    code == 500) {
                ResponseBody body = httpException.response().errorBody();
                try {
                    String errorData = body.string();
                    SLog.d(errorData);
                    return gson.fromJson(errorData, ServerFailureBean.class);
                } catch (Exception gsonE) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return null;
    }

    /**
     * // TODO 正式发版时修改
     */
    public String failureMessage(Context context) {
        if (serverFailureBean != null) {
            return serverFailureBean.getMessage();
        } else if (e instanceof JsonParseException ||
                e instanceof ParseException ||
                e instanceof JSONException) {
            return "JSON解析异常";
        } else if (e instanceof ConnectException) {
            return "网络连接异常";
        } else if (e instanceof SSLHandshakeException) {
            return "证书有问题,请检查证书";
        } else if (e instanceof SocketTimeoutException) {
            return "网络超时";
        } else if (e instanceof HttpException) {
            return "服务器异常";
        }
//        return "未知异常，请检查Throwable";
        return "未知异常，请检查网络";
    }


}
